#! /usr/bin/perl -w

use strict;
use Carp;

use Data::Dumper;
use IO::Socket;
use XML::Simple;
use Sys::Hostname;

use constant BUFSIZE => 2048;

my $xml    = new XML::Simple;
my $host   = hostname;
my $port   = shift || '10280';
my $socket = new IO::Socket(
    Domain    => PF_INET,
    Proto     => getprotobyname('tcp'),
    LocalAddr => $host,
    LocalPort => $port,
    Listen    => 1,
    Reuse     => 1,
) or die $@;

my $buffer;

print "Waiting to do service...\n";
while ( my $client = $socket->accept ) {
    $client->autoflush(1);

    print "Client: ", $client->peerhost, " Connected..\n";
    $client->send( "OK,Speak.\n", 0 );

    print $client->recv( $buffer, BUFSIZE, 0 );
    my $server_needed = get_server_status();
    my $client_needed = process_data($buffer);
    my @action        = solve_problem( $server_needed, $client_needed );
    take_action( @action, $client );
}

sub get_server_status {
    return 0;
}

sub process_data {
    if ( @_ > 1 ) { carp "Only can have one input, not @_."; }
    my ($data_in_xml) = @_;
    print Dumper($data_in_xml);
    my $data_in_hash = $xml->XMLin($data_in_xml);
    print "Hash: " . Dumper($data_in_hash);
    my $nodes_needed = 23;
    return $nodes_needed;
}

sub solve_problem {
    if ( @_ > 2 ) { carp "Only can have one input, not @_."; }
    my ( $server_needed, $client_needed ) = @_;
    my @result = ( 'CLIENT', 12 );
}

sub take_action {
    if ( @_ > 3 ) { carp "Only can have one input, not @_."; }
    my ( $object, $nodes_needed, $client ) = @_;

    print $client "Data OK, " 
      . $object
      . " need reboot "
      . $nodes_needed
      . ", bye!\n";
}
